<?php

namespace App\Http\Middleware;

use AdminMenu;
use Closure;
use App\Repositories;
class AdminMenuMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        view()->composer('*', function ($view) {
            //共享菜单数据
            $menus = Repositories\Admin\MenuRepository::getInstance()->getMenusAllList();
            //  单页码
            $pageList = Repositories\Portal\CategoryRepository::getInstance()->getPageList();
            $pageList = list_to_tree($pageList->toArray());
            foreach ($menus as $key=>&$value) {
                //  如果时门户模块 则新增单页面菜单
                if ($value['id'] == 18) {
                    $n = count($value['_child']);
                    foreach ($pageList as $k=>$val) {
                        $value['_child'][$k+$n] = [
                            'name' => $val['title'],
                            'icon' => '',
                            'slug' => 'admin-portal-page-edit',
                            'url' => get_admin_url('portal/page/edit', ['category_id'=>$val['id']]),
                            'menu_type' => 1,
                            'is_developer' => 0,
                            'pid' => $value['id'],
                            'sort' => 0,
                        ];
                        if (!empty($val['_child'])) {
                            foreach ($val['_child'] as $i=>$v) {
                                $value['_child'][$k+$n]['_child'][$i] = [
                                    'name' => $v['title'],
                                    'icon' => '',
                                    'slug' => 'admin-portal-page-edit',
                                    'url' => get_admin_url('portal/page/edit', ['category_id' => $v['id']]),
                                    'menu_type' => 1,
                                    'is_developer' => 0,
                                    'pid' => $val['id'],
                                    'sort' => 0,
                                    '_child' => [],
                                ];
                            }
                        }
                    }
                }
            }
            $view->with('menus', $menus);
        });
        return $next($request);
    }
}
